package com.java.module.chat.util.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpRequestHandler<br>
 * 身份鉴权
 * 
 * @author yilabao
 * @date 2021年9月29日
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger LOG = LoggerFactory.getLogger(HttpRequestHandler.class);

    public static final AttributeKey<Long> CHANNEL_USER_KEY = AttributeKey.valueOf("uid");

    private final String websocketPath;

    public HttpRequestHandler(String websocketPath) {
        this.websocketPath = websocketPath;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String uri = request.uri();
        Long uid = ChatKit.getUidByUri(uri);
        if (uid == null) {
            LOG.warn("用户鉴权失败：uri: {}", uri);
            ctx.close();
            return;
        }
        request.setUri(websocketPath);
        ctx.channel().attr(CHANNEL_USER_KEY).set(uid);
        ChatHandler.login(ctx, uid);
        ctx.fireChannelRead(request.retain());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}